<template>
  <div class="about">
    <img alt="Vue logo" :src="logoImg">
    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" pageName="About"/>
    <h1>This is an about page</h1>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="loadData">Load Data</button>
    <button @click="postData">Post Data</button>
    <button @click="loadUserData">Load User Data</button>
    <div v-if="data">
      <h2>Fetched Data:</h2>
      <pre>{{ data }}</pre>
    </div>
    <div v-if="postResponse">
      <h2>Post Response:</h2>
      <pre>{{ postResponse }}</pre>
    </div>
    <div v-if="userData">
      <h2>User Data:</h2>
      <pre>{{ userData }}</pre>
    </div>

    <h2>Upload Image</h2>
    <input type="file" @change="onFileChange" accept="image/*" />
    <div v-if="loading">Uploading...</div>
    <div v-if="previewUrl">
      <h3>Preview Before Upload:</h3>
      <img :src="previewUrl" alt="Image Preview" style="max-width: 200px;" />
    </div>
    <div v-if="uploadedUrl">
      <h3>Uploaded Image:</h3>
      <img :src="uploadedUrl" alt="Uploaded Image" style="max-width: 200px;" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useStore } from '@/stores/myStore'
import { fetchData } from '@/utils/fetch'
import { API_URLS } from '@/utils/api'
import { compressImage } from '@/utils/compressImage'
import HelloWorld from '@/components/HelloWorld.vue'
import logoImg from '@/assets/logo.png'
interface PostData {
  title: string;
  body: string;
  userId: number;
}

interface UploadResponse {
  url: string;
  [key: string]: any;
}

const store = useStore()
const count = computed(() => store.count)
const doubleCount = computed(() => store.doubleCount)
const { increment, loadUserData } = store

const data = ref<any>(null)
const postResponse = ref<any>(null)
const previewUrl = ref<string | null>(null)
const uploadedUrl = ref<string | null>(null)
const loading = ref<boolean>(false)

const userData = computed(() => store.userData)

const loadData = async (): Promise<void> => {
  try {
    data.value = await fetchData(API_URLS.getPost, {}, 500)
  } catch (error) {
    console.error('Error loading data:', error)
  }
}

const postData = async (): Promise<void> => {
  try {
    const payload: PostData = { title: 'foo', body: 'bar', userId: 1 }
    postResponse.value = await fetchData<PostData>(API_URLS.createPost, {
      method: 'POST',
      body: JSON.stringify(payload),
      headers: {
        'Content-Type': 'application/json'
      }
    }, 500)
  } catch (error) {
    console.error('Error posting data:', error)
  }
}

const onFileChange = (event: Event): void => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    previewUrl.value = URL.createObjectURL(file)
    compressImage(file).then(compressedFile => {
      uploadImage(compressedFile)
    }).catch(error => {
      console.error('Error compressing image:', error)
    })
  }
}

const uploadImage = async (file: File): Promise<void> => {
  loading.value = true
  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await fetchData<UploadResponse>(API_URLS.uploadImage, {
      method: 'POST',
      body: formData
    })
    uploadedUrl.value = response.url
  } catch (error) {
    console.error('Error uploading image:', error)
  } finally {
    loading.value = false
  }
}
</script>
